package com.gonsin.gview.common.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.gonsin.base.exceptions.MyException;
import com.gonsin.gview.common.auth.UserResultCode;
import com.gonsin.gview.common.bean.UserMenuBean;
import com.gonsin.gview.common.mapper.UserMenuMapper;
import com.gonsin.gview.common.po.MenuPo;
import com.gonsin.gview.common.po.MenuSearchPo;
import com.gonsin.gview.common.po.MenuSortPo;
import com.gonsin.gview.common.services.IMenusService;
import com.gonsin.gview.common.utils.KeyOnlyUtils;
import com.gonsin.gview.common.utils.SessionKeys;
import com.gonsin.gview.logic.config.GViewMenuService;
import com.gonsin.gview.model.menu.GViewMenu;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@Service("gviewCommonMenuService")
public class MenusServiceImpl implements IMenusService, ApplicationListener<ApplicationStartingEvent> {

//    private Map<String, GViewMenu> menusMap = new HashMap<>();
    private List<MenuPo> allMenus = new ArrayList<>();

    @Autowired private UserMenuMapper userMenuMapper;

    @Override
    public void addMenu(MenuPo menu) {

        // 判断菜单的name是否唯一
        MenuPo sameName = allMenus.stream().filter(m -> m.getName().equals(menu.getName())).findFirst().orElse(null);
        if(sameName != null){
            throw new MyException(UserResultCode.MENU_SAME_NAME,
                    String.format("菜单name不能重复！！请查看菜单标题为 【%s】，name为【%s】的地方", menu.getTitle(), menu.getName()));
        }
        allMenus.add(menu);
        allMenus.sort(Comparator.comparingInt(MenuPo::getIndex));
//        GViewMenu gm = new GViewMenu(menu.getName(), menu.getTitle(), menu.getParent(), menu.getUrl(), menu.getIcon());
//        menusMap.put(menu.getName(), gm);
    }


    /**
     * 获取所有菜单
     * @return
     */
    @Override
    public List<String> getAllPermissions(){
        return allMenus.stream().map(m -> m.getName()).collect(Collectors.toList());
    }

    @Override
    public List<MenuPo> getSystemMenus() {
        return allMenus;
    }


    /**
     * 获取所有菜单
     */
    @Override
    public List<UserMenuBean> getAllMenus(String edificeKey, MenuSearchPo searchPo){
        if(BooleanUtils.isFalse(searchPo.getCurrentMenu())){
            return allMenus.stream().map(m -> {
                UserMenuBean menu = new UserMenuBean();
                menu.setEdificeKey(edificeKey);
                menu.setSort(m.getIndex());
                menu.setIcon(m.getIcon());
                menu.setParent(m.getParent());
                menu.setName(m.getName());
                menu.setTitle(m.getTitle());
                menu.setUrl(m.getUrl());
                return menu;
            }).collect(Collectors.toList());
        }
        return userMenuMapper.selectByEdificeKey(edificeKey);
    }

    @Override
    public List<UserMenuBean> saveMenus(String edificeKey, MenuSortPo menuSortPo) {
        if(menuSortPo == null || CollectionUtils.isEmpty(menuSortPo.getMenus())){
            return new ArrayList<>();
        }
        for(UserMenuBean newMenu : menuSortPo.getMenus()){

//            if(!edificeKey.equals(newMenu.getEdificeKey())){
//                throw new MyException(UserResultCode.MENU_ERROR, "菜单项必须与edificeKey匹配");
//            }

            // 原有的菜单直接修改
            if(!StringUtils.isEmpty(newMenu.getMenuKey())){
                UserMenuBean originMenu = userMenuMapper.getMenu(newMenu.getMenuKey());
                if(originMenu == null){
                    continue;
                }

                if(!originMenu.getEdificeKey().equals(newMenu.getEdificeKey())){
                    continue;
                }

                BeanUtil.copyProperties(newMenu, originMenu,
                        CopyOptions.create().setIgnoreNullValue(true)
                                .setIgnoreProperties("menuKey", "edificeKey"));
                userMenuMapper.updateById(originMenu);
                continue;
            }

            // 新增的菜单直接添加
            newMenu.setMenuKey(KeyOnlyUtils.general("menu"));
            newMenu.setEdificeKey(edificeKey);
            userMenuMapper.insert(newMenu);
        }


        // 不存在的菜单直接删除
        List<UserMenuBean> currents = userMenuMapper.selectByEdificeKey(edificeKey);
        Iterator<UserMenuBean> iterator = currents.iterator();
        while(iterator.hasNext()){
            UserMenuBean u = iterator.next();
            if(menuSortPo.getMenus().contains(u)){
                continue;
            }
            userMenuMapper.deleteById(u.getMenuKey());
            iterator.remove();
        }
        return currents;
    }

    @Override
    public void onApplicationEvent(ApplicationStartingEvent event) {
    }
}
